package com.zhibi.util.tuling;

import java.io.IOException;


import com.google.gson.Gson;
import com.zhibi.util.http.HttpRespons;
import com.zhibi.util.http.HttpUtil;
import com.zhibi.util.tuling.domain.TLCookbooks;
import com.zhibi.util.tuling.domain.TLFlights;
import com.zhibi.util.tuling.domain.TLLink;
import com.zhibi.util.tuling.domain.TLNews;
import com.zhibi.util.tuling.domain.TLText;
import com.zhibi.util.tuling.domain.TLTrains;

public class TLUtil {

	private static final String URL = "http://www.tuling123.com/openapi/api";
	private static final String APIKEY = "293dc286ebcc11c54d856960eb943040";

	public static final int CODE_TEXT = 100000;
	public static final int CODE_LINK = 200000;
	public static final int CODE_NEW = 302000;
	public static final int CODE_TRAIN = 305000;
	public static final int CODE_FLIGHT = 306000;
	public static final int CODE_COOKBOOK = 308000;
	
	/**
	 * 得到响应信息
	 * @param info
	 * @return
	 */
	public static String getContent(String info){
		String url =URL + "?key=" + APIKEY + "&info=" +info;
		HttpRespons httpRespons = null;
		try {
			httpRespons = HttpUtil.sendGet(url);
			return httpRespons.getContent();
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 封装实体
	 * @param info
	 * @return
	 */
	public static TLText getText(String info){
		String json = TLUtil.getContent(info);
		Gson gson = new Gson();
		TLText tlText= gson.fromJson(json, TLText.class);
		switch (tlText.getCode()) {
		case CODE_TEXT:
			return tlText;
		case CODE_LINK:
			return getLink(json);
		case CODE_NEW:
			return getNew(json);
		case CODE_TRAIN:
			return getTrain(json);
		case CODE_FLIGHT:
			return getFlight(json);
		case CODE_COOKBOOK:
			return getCookbook(json);
		default:
			break;
		}
		return tlText;
	}

	/**
	 * 得到菜谱
	 * @param json
	 * @return
	 */
	public static TLCookbooks getCookbook(String json) {
		Gson gson = new Gson();
		return gson.fromJson(json, TLCookbooks.class);
	}

	/**
	 * 得到航班
	 * @param json
	 * @return
	 */
	public static TLFlights getFlight(String json) {
		Gson gson = new Gson();
		return gson.fromJson(json, TLFlights.class);
	}

	/**
	 * 得到列车
	 * @param json
	 * @return
	 */
	private static TLTrains getTrain(String json) {
		Gson gson = new Gson();
		return gson.fromJson(json, TLTrains.class);
	}

	/**
	 * 得到新闻
	 * @param json
	 * @return
	 */
	public static TLNews getNew(String json) {
		Gson gson = new Gson();
		return gson.fromJson(json, TLNews.class);
	}

	/**
	 * 得到链接
	 * @param json
	 * @return
	 */
	public static TLLink getLink(String json) {
		Gson gson = new Gson();
		return gson.fromJson(json, TLLink.class);
	}
}
